package com.foreverwin.mes.production.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.foreverwin.mes.common.constants.HandleBOConstants;
import com.foreverwin.mes.core.exception.BusinessException;
import com.foreverwin.mes.core.utils.DateUtil;
import com.foreverwin.mes.core.utils.I18nUtil;
import com.foreverwin.mes.core.utils.StringUtils;
import com.foreverwin.mes.meapi.model.Certification;
import com.foreverwin.mes.meapi.model.Resrce;
import com.foreverwin.mes.meapi.service.CertificationService;
import com.foreverwin.mes.meapi.service.ResrceService;
import com.foreverwin.mes.production.mapper.StationMapper;
import com.foreverwin.mes.production.model.Station;
import com.foreverwin.mes.production.model.StationCertification;
import com.foreverwin.mes.production.model.StationResource;
import com.foreverwin.mes.production.service.StationCertificationService;
import com.foreverwin.mes.production.service.StationResourceService;
import com.foreverwin.mes.production.service.StationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * <p>
 * 岗位 服务实现类
 * </p>
 *
 * @author syngna
 * @since 2018-11-28
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class StationServiceImpl extends ServiceImpl<StationMapper, Station> implements StationService {


    @Autowired
    private StationMapper stationMapper;

    @Autowired
    private ResrceService resourceService;

    @Autowired
    private CertificationService certificationService;

    @Autowired
    private StationResourceService stationResourceService;

    @Autowired
    private StationCertificationService stationCertificationService;

    @Override
    public List<Station> selectList(String site) {

        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("SITE", site);
        return stationMapper.selectByMap(paramMap);
    }

    @Override
    public Station getStation(String site, String station) {

        Station stationModel = new Station();
        stationModel.setSite(site);
        stationModel.setStation(station);
        return stationMapper.selectOne(stationModel);
    }


    @Override
    public void stationSave(String site, String user, String modifiedDateTime, Station station, List<Map> certificationList, List<Map> resourceList) throws BusinessException {

        //now Date
        Date nowTime = new Date();
        String stationBo = null;

        //查询岗位是否存在
        Station queryModel = new Station();
        queryModel.setSite(site);
        queryModel.setStation(station.getStation());
        queryModel = stationMapper.selectOne(queryModel);

        /**
         * 岗位信息存储
         */
        if (queryModel != null) {

            //岗位更新
            if (StringUtils.isBlank(modifiedDateTime)) {
                throw BusinessException.build("岗位【" + station.getStation() + "】已存在,请先检索");
            }

            String curModifiedDateTime = DateUtil.formatDate(queryModel.getModifiedDateTime(), "yyyy-MM-dd HH:mm:ss.SSS");
            if (!curModifiedDateTime.equals(modifiedDateTime)) {
                throw BusinessException.build("岗位【 " + station.getStation() + "】已修改,请重新检索");
            }

            stationBo = queryModel.getHandle();
            station.setHandle(stationBo);
            station.setCreateUser(queryModel.getCreateUser());
            station.setCreatedDateTime(queryModel.getCreatedDateTime());
            station.setModifyUser(user);
            station.setModifiedDateTime(nowTime);
            stationMapper.updateAllColumnById(station);

        } else {

            //岗位新增
            Station addModel = new Station();
            stationBo = HandleBOConstants.STATION_BO + ":" + site + "," + station.getStation();
            addModel.setHandle(stationBo);
            addModel.setSite(site);
            addModel.setStation(station.getStation());
            addModel.setDescription(station.getDescription());
            addModel.setStatus(station.getStatus());
            addModel.setCreateUser(user);
            addModel.setCreatedDateTime(nowTime);
            addModel.setModifyUser(user);
            addModel.setModifiedDateTime(nowTime);
            stationMapper.insert(addModel);
        }

        /**
         * 岗位下证明存储
         */
        //删除岗位下全部证明
        stationCertificationService.deleteCertificationByStation(stationBo);

        if (certificationList.size() > 0) {

            String status701Bo = StringUtils.genHandle(HandleBOConstants.STATUS_BO, site, "701");
            //岗位 证明关联数据组装
            StationCertification stationCertification = null;
            List<StationCertification> list = new ArrayList<StationCertification>();
            for (int i = 0; i < certificationList.size(); i++) {

                Map map = certificationList.get(i);
                stationCertification = new StationCertification();
                String certification = (String) map.get("certification");
                String certificationBo = "CertificationBO:" + site + "," + certification;
                //证明是否存在
                EntityWrapper<Certification> entityWrapper = new EntityWrapper<Certification>();
                entityWrapper.eq("SITE", site);
                entityWrapper.eq("CERTIFICATION", certification);
                Certification cerInfo = certificationService.selectOne(entityWrapper);
                if (cerInfo == null) {
                    throw new RuntimeException(I18nUtil.getI18nText("production.noneCertification.error", new String[]{certification}));
                } else if (!status701Bo.equals(cerInfo.getStatusBo())) {
                    throw BusinessException.build("证明【" + certification + "】非【已启用】状态，不可用");
                }

                stationCertification.setHandle("StationCertificationBO:" + site + "," + station.getStation() + "," + certification);
                stationCertification.setStationBo(stationBo);
                stationCertification.setCertificationBo(certificationBo);
                stationCertification.setCreateUser(user);
                stationCertification.setCreatedDateTime(nowTime);
                stationCertification.setModifyUser(user);
                stationCertification.setModifiedDateTime(nowTime);
                list.add(stationCertification);
            }

            stationCertificationService.insertBatch(list);
        }


        /**
         * 岗位下设备存储
         */
        //删除岗位下所有设备
        stationResourceService.deleteResourceByStation(stationBo);

        if (resourceList.size() > 0) {

            //岗位设备绑定
            StationResource stationResource = null;
            List<StationResource> list = new ArrayList<StationResource>();
            for (int i = 0; i < resourceList.size(); i++) {

                Map map = resourceList.get(i);
                String resource = (String) map.get("resrce");
                String resourceBo = "ResourceBO:" + site + "," + resource;
                //资源是否存在
                Resrce rsInfo = resourceService.selectById(resourceBo);
                if (rsInfo == null) {
                    throw new RuntimeException(I18nUtil.getI18nText("production.noneResource.error", new String[]{resource}));
                }

                stationResource = new StationResource();
                stationResource.setHandle("StationCertificationBO:" + site + "," + station.getStation() + "," + resource);
                stationResource.setStationBo(stationBo);
                stationResource.setResourceBo(resourceBo);
                stationResource.setCreateUser(user);
                stationResource.setCreatedDateTime(nowTime);
                stationResource.setModifyUser(user);
                stationResource.setModifiedDateTime(nowTime);
                list.add(stationResource);
            }
            stationResourceService.insertBatch(list);
        }

    }

    @Override
    public int stationDelete(String site, String station) throws BusinessException {

        //岗位查询
        Station stationModel = this.getStation(site, station);
        if (stationModel == null) {
            throw BusinessException.build("岗位： " + station + "不存在");
        }
        String handle = stationModel.getHandle();

        //删除岗位下全部证明
        stationCertificationService.deleteCertificationByStation(handle);
        //删除岗位下全部设备
        stationResourceService.deleteResourceByStation(handle);
        //删除岗位信息
        int count = stationMapper.deleteById(handle);

        return count;
    }

    @Override
    public boolean updateById(Station station) {
        if (super.updateById(station)) {
            return true;
        } else {
            throw new RuntimeException(I18nUtil.getI18nText("Common.UpdateByOther.Error"));
        }
    }

}